import request from '@/request'
import config from './modules'
type RequestMethod = 'get' | 'post' | 'put' | 'delete' | 'patch'
export default new Proxy({} as Record<keyof typeof config, Function>, {
  get(_, key: keyof typeof config) {
    const cfgObj = config[key]
    if (!cfgObj) throw new Error(`未知接口：${String(key)}`)
    return async (...args: any[]) => {
      const [payload, extra = {}] = args
      const axiosCfg = {
        ...cfgObj,
        ...extra,
        ...payload,
      }
      let { method, url, ...rest } = axiosCfg
      url = url.replace(/:(\w+)/g, (_:any, key:any) => {
        const value = payload[key]
        if (value === undefined) {
          throw new Error(`缺少路径参数: ${key}`)
        }
        return encodeURIComponent(value)
      })
      let res = null
      let err = null
      try {
        window.$isLoading.value = true
        res = await request[method as RequestMethod](url, rest)
      } catch (e) {
        err = e
      } finally {
        window.$isLoading.value = false
        return [res, err]
      }
    }
  },
})
